package com.csnf.order.exception;

import com.alibaba.csp.sentinel.adapter.spring.webmvc_v6x.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.csnf.pojo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.PrintWriter;

@Component
public class MyBlockExceptionHandle implements BlockExceptionHandler {

    //可以将java对象转成json字符串
    ObjectMapper objectMapper = new ObjectMapper();
    //异常处理
    @Override
    public void handle(HttpServletRequest request,
                       HttpServletResponse response,
                       String s, BlockException e) throws Exception {
        //设置编码格式
        //response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        Result r = Result.error(500,s+"被sentinel限制"+e.getClass(),null);
        //将r转成json输出
        String json = objectMapper.writeValueAsString(r);

        writer.write(json);
        writer.flush();
    }
}
